using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace CapstoneProject.Activities
{
    [Activity(Label = "Add Account")]
    public class ChooseFIActivity : Activity
    {
        private ListView bankList;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.ChooseFI);

            Button searchButton = FindViewById<Button>(Resource.Id.SearchButton);
            searchButton.Click += RefreshBanks;

            bankList = FindViewById<ListView>(Resource.Id.BankList);
            bankList.ItemClick += SelectBank;
        }

        private List<string> ReturnResults(string search)
        {
            List<string> list = new List<string>();
            
            OFXHome ofxh = new OFXHome();
            foreach (string s in ofxh.AllBanks())
            {
                if (s.ToLower().Contains(search.ToLower()))
                {
                    list.Add(s);
                }
            }
            return list;
        }

        private void RefreshBanks(object sender, EventArgs e)
        {
            TextView error = FindViewById<TextView>(Resource.Id.ChooseBankError);
            EditText searchField = FindViewById<EditText>(Resource.Id.BankSearchField);
            if (!String.IsNullOrEmpty(searchField.Text))
            {
                var banks = ReturnResults(searchField.Text);
                if (banks.Count == 0)
                {
                    error.Text = "No results.";
                }
                else
                {
                    bankList.Adapter = new BankListAdapter(this, banks);
                }
            }
            else
            {
                error.Text = "Please don't leave the search field blank.";
            }
        }

        private void SelectBank(object sender, ItemEventArgs e)
        {
            var bank = ((BankListAdapter)bankList.Adapter).GetBank(e.Position);
            string username = Intent.GetStringExtra("User");
            Intent i = new Intent();
            i.SetClass(this, typeof(EnterAccCredActivity));
            i.AddFlags(ActivityFlags.NewTask);
            i.PutExtra("User", username);
            i.PutExtra("Bank", bank);
            StartActivity(i);
        }
    }
}